/* pages/order/orderDetail/orderDetail.js */
import PagePromoterUtil, {
  PagePromoter
} from '../../../data/common/pagePromoter';
import AppSceneUtil from '../../../data/common/appScene';
import SessionUtil, { JxbHttpClient } from "../../../data/session/session"
const Common = require('../../../utils/common.js');
import InteractionUtil from '../../../shell/ui/interaction';

Page({
  data: {
    token: '',
    orderId: 0,
    Product: {},
	
	cpboxOpen:false,
	payPrice:0
  },
  onLoad: function (options) {
    // 开启转发按钮
    PagePromoterUtil.showShareMenu(true).then()
    // 页面初始化 options为页面跳转所带来的参数
    SessionUtil.getInstance().then(session => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this)
      this.setData({
        token: session.token
      });
      if (options.itemId) {
        this.setData({
          orderId: options.itemId
        })
      }
      wx.setNavigationBarTitle({
        title: '订单详情'
      })
      wx.showLoading({
        title: '数据加载中',
      })
      this.itemInfo();
    })

  },
  onShow: function () {
    getApp().getSaleMode()
    SessionUtil.getInstance().then(() => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this, false)
    })
  },
  itemInfo: function (action = '') {
    // 加载详情
    console.log('itemInfo');
    var page = this;
    var orderId = page.data.orderId;

    if (action == 'Refresh') {
      console.log('is Refresh!');
      wx.stopPullDownRefresh();
    }

    JxbHttpClient.getClient().get({
      url: '/AppMaster/PosOrder/orderDetail',
      data: {
        orderId: orderId,
      }
    }).then(jxbResp=>{
      wx.hideLoading();
      var Product = jxbResp.data;
      var itemids = [];
      var limits = [];
      for (var z = 0; z < Product.activity_list.length; z++) {
        if (Product.activity_list[z].activity_category == 6) {
          itemids = itemids.concat(Product.activity_list[z].item_ids);
        }
        if (Product.activity_list[z].activity_category == 4) {
          limits = limits.concat(Product.activity_list[z].item_ids);
        }
      }
      for (var j = 0; j < Product.item_list.length; j++) {
        var a = Common.contains(itemids, Product.item_list[j].item_id),
          b = Common.contains(limits, Product.item_list[j].item_id);
        if (a && b) {
          Product.item_list[j].activity_list = ['秒杀', '限购']
        } else {
          if (a) {
            Product.item_list[j].activity_list = ['秒杀'];
          }
          if (b) {
            Product.item_list[j].activity_list = ['限购'];
          }
        }
        if (!Product) {
          Common.Alert('错误提示',jxbResp.message);
          wx.hideLoading();
          return;
        }
        console.log(Product);
        page.setData({
          Product: Product
        });
        // 关闭加载
        wx.hideLoading();
      }
    }).catch(err=>{
      console.log(err.message);
      Common.Alert('错误提示',err.message);
    })
  },
  onPullDownRefresh: function () {
    // 下拉刷新
    var page = this;
    wx.showLoading({
      title: '数据加载中',
    })
    page.itemInfo('Refresh');
  },
  onShareAppMessage: function () {
    // 构造并返回自定义数据
    return (new PagePromoter(this.route, {
        itemId: this.data.itemId
      }))
      .setShareTitle(this.data.itemInfo.productName)
      .buildShareInfo()
  },
  returnHome: function () {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  goDetail: function (e) {
    var itemId = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/order/orderDetail/orderDetail?itemId=' + itemId
    })
  },
  complete: function (e) {
    var order = e.currentTarget.id.split('-'),
      page = this;
    Common.my_request({
      url: '/AppMaster/PosOrder/setOrderFinished', //仅为示例，并非真实的接口地址
      data: {
        orders_id: page.data.orderId,
        account_id: page.data.Product.account_id,
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.result == 0) {
          page.itemInfo();
        } else {
          wx.showToast({
            title: res.data.message,
            image: '',
            duration: 2000
          });
        }
      }
    })
  },
  deleted: function (e) {
    var pags = this,
      order = e.currentTarget.id.split('-')
    wx.showModal({
      title: '提示',
      content: '确认取消订单吗？',
      success: function (res) {
        if (res.confirm) {
          pags.deletes(order)
          console.log('用户点击确定')
        } else if (res.cancel) {
          wx.hideLoading()
        }
      }
    })
  },
  deletes: function (order) {
    var page = this;
    Common.my_request({
      url: '/AppMaster/PosOrder/delete', //仅为示例，并非真实的接口地址
      data: {
        orders_id: order[0],
        account_id: order[1],
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.result == 0) {
          page.itemInfo();
          wx.showToast({
            title: '删除成功',
            image: '',
            duration: 2000
          });
        } else {
          wx.showToast({
            title: '删除失败',
            image: '../../images/fail.png',
            duration: 2000
          });
        }
      }
    })
  },
  payment: function (e) {
    var order = e.currentTarget.id.split('-'),
      itemId = this.data.orderId;
    wx.navigateTo({
      url: '/pages/order/pay/pay?orderno=' + order[0] + "&paymoney=" + order[1] + '&itemId = false'
    })
  },
  goInvoice() {
    const {
      Product
    } = this.data
    const {
      orders_id,
      pay_amount
    } = Product
    wx.$http().request({
      url: '/AppMaster/PosOrder/getOrderInvoiceMessage',
      data: {
        order_id: orders_id
      },
      method: 'POST'
    }).then(res => {
      const {
        data
      } = res
      const {
        invoice_state,
        invoice_data,
        invoice_state_msg
      } = data
      if (invoice_state * 1 === 0) {
        InteractionUtil.showNotice(invoice_state_msg)
      } else {
        wx.navigateTo({
          url: '/subPage/invoice/index',
          success: res => {
            res.eventChannel.emit('acceptData', {
              data,
              amount: pay_amount,
              orderId: orders_id
            })
          }
        })
      }
    })
  },
  
  
  openCPBox(){
  	  const Product = this.data;
  	  this.setData({
  		  cpboxOpen:true
  	  })
  },  
  closeCPBox(){
	  const Product = this.data;
	  this.setData({
		  cpboxOpen:false
	  })
  },
  numberPayPrice(e){
	  const Product = this.data;
	  const payPrice = e.detail.value;
	  console.log(payPrice);
	  this.setData({
		  payPrice:payPrice
	  })
  },
  
  ChangePrice(){
	  const Data = this.data;
	  const min_can_set_pay_amount = Data.Product.edit_pay_amount.data.min_can_set_pay_amount;
	  const payPrice = Data.payPrice;
	  const itemId = Data.orderId;
	  const page = this;
	  
	  if(!payPrice){
		  wx.showToast({
		    title: '请输入金额',
		    icon: 'none',
		    duration: 2000
		  })
		  return false;
	  }else if(payPrice < min_can_set_pay_amount){
		  wx.showToast({
			title: '最低可输入金额 '+min_can_set_pay_amount+' 元',
			icon: 'none',
			duration: 2000
		  })
		  return false;
	  }
	  
	  Common.my_request({
	    url: '/AppMaster/PosOrder/orderChangePrice', //仅为示例，并非真实的接口地址
	    data: {
	      order_id: itemId,
	      pay_amount: payPrice,
	    },
	    success: function (res) {
	      console.log(res.data)
	      if (res.data.result == 0) {
			wx.showToast({
			  title: '金额修改成功',
			  icon: 'success',
			  duration: 2000
			})
			page.closeCPBox();
			page.itemInfo('Refresh');
	      } else {
	        wx.showToast({
	          title: res.data.message,
	          image: '',
	          duration: 2000
	        });
	      }
	    }
	  })
	  
  }
  
})